package com.own.business.pay.module.alipay.controller;

import com.own.aop.login.LoginIgnore;
import com.own.business.pay.common.em.PayEnum;
import com.own.business.pay.core.method.TradeSuccessHandlerService;
import com.own.business.pay.core.service.BillHistoryService;
import com.own.component.common.base.controller.BaseController;
import com.own.component.common.util.executor.ExecutorUtil;
import com.own.constant.ConstantApiPrefix;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * AlipayController
 *
 * @author chenxueli
 * @date 2023-08-17 16:42:00
 */
@Slf4j
@RestController
@RequestMapping(ConstantApiPrefix.BASE_API_V1_PREFIX + "pay/alipay")
public class AlipayController extends BaseController {

    @Resource
    private List<TradeSuccessHandlerService> tradeSuccessHandlerServiceList;

    @Resource
    private BillHistoryService billHistoryService;
    @Resource
    private ExecutorUtil executorUtil;

    // https://api.xx.com/receive_notify.htm?
    // gmt_payment=2015-06-11 22:33:59&
    // notify_id=42af7baacd1d3746cf7b56752b91edcj34&
    // seller_email=testyufabu07@alipay.com&
    // notify_type=trade_status_sync&
    // sign=kPbQIjX+xQc8F0/A6/AocELIjhhZnGbcBN6G4MM/HmfWL4ZiHM6fWl5NQhzXJusaklZ1LFuMo+lHQUELAYeugH8LYFvxnNajOvZhuxNFbN2LhF0l/KL8ANtj8oyPM4NN7Qft2kWJTDJUpQOzCzNnV9hDxh5AaT9FPqRS6ZKxnzM=&
    // trade_no=2015061121001004400068549373&
    // out_trade_no=21repl2ac2eOutTradeNo322&
    // gmt_create=2015-06-11 22:33:46&
    // seller_id=2088211521646673&
    // notify_time=2015-06-11 22:34:03&
    // subject=FACE_TO_FACE_PAYMENT_PRECREATE中文&
    // trade_status=TRADE_SUCCESS&
    // sign_type=RSA2

    @LoginIgnore
    @PostMapping("callback")
    public String callback(
            HttpServletRequest request
    ) {
        var outTradeNo = request.getParameter("out_trade_no");
        var outRequestNo = request.getParameter("out_biz_no");
        log.info(outTradeNo);
        log.info(outRequestNo);
        log.info(request.getQueryString());
        if (StringUtils.isNotBlank(outRequestNo)) {
            executorUtil.execute(() -> billHistoryService.notifyRefundSuccess(PayEnum.Method.ALIPAY, outRequestNo, request.getQueryString()));
            tradeSuccessHandlerServiceList.forEach(method -> method.pay(PayEnum.Method.ALIPAY, outRequestNo));
        } else {
            executorUtil.execute(() -> billHistoryService.notifySuccess(PayEnum.Method.ALIPAY, outTradeNo, request.getQueryString()));
            tradeSuccessHandlerServiceList.forEach(method -> method.pay(PayEnum.Method.ALIPAY, outTradeNo));
        }
        return "success";
    }

}
